﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Caching.Memory;
using OA.BLL;

using OA.Core;
using OA.Core.DataAccessHelper;
using OA.Core.EF;
using OA.Core.Helper;
using OA.Model;
using OA.Model.Mapper;
using OA.Model.View;
using OA.Web.Attribute;
using OA.Web.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;


namespace OA.Web.Areas.Member.Controllers
{
    public class StatisticController : BaseMemberController
    {
        private IMemoryCache _cache;
        private ICookie _cookie;
        public StatisticController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
            _cookie = cookie;
        }

        [MyActionFilter("888", "customFormID")]
        public IActionResult Index(int customFormID)
        {
            ViewBag.customFormID = customFormID;
            return View();
        }


        [MyActionFilter("888", "customFormID")]
        public IActionResult GetData(int customFormID, string empName, string startTime, string endTime, int page = 1, int limit = 15)
        {
            CustomForm infoCustomForm = this.GetInfo<CustomForm>(customFormID);
            if (infoCustomForm == null)
            {
                var errorRresult = new
                {
                    code = "400",
                    msg = "您查看的单据类型不存在"
                };
                return Json(errorRresult);
            }
            ViewBag.PageKey = "888" + customFormID.ToString("D3");
            ViewBag.CustomForm = infoCustomForm;
            ViewBag.CustomFormID = customFormID;
            ViewBag.EmpName = empName;
            ViewBag.CustomFormID = customFormID;
            ViewBag.StartTime = startTime;
            ViewBag.EndTime = endTime;

            string empID = Info.EmpID;

            EmployeeCustomForm infoEmployeeCustomForm = this.dbContextFactory.DbContext.EmployeeCustomForm.Where(m => m.EmpID == empID && m.CustomFormID == customFormID && m.Status != -1 && m.TypeID == 1).FirstOrDefault();
            if (infoEmployeeCustomForm == null)
            {
                var errorRresult = new
                {
                    code = "400",
                    msg = "您没有当前单据的统计汇总权限"
                };
                return Json(errorRresult);
            }

            Expression<Func<Voucher, bool>> where = m => m.Status == 4;
            if (!string.IsNullOrWhiteSpace(empName))
            {
                where = where.AndAlso(m => m.SponsorName == empName);
            }

            if (!string.IsNullOrWhiteSpace(startTime))
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(startTime, out dt))
                {
                    where = where.AndAlso(m => m.FinishTime >= dt);
                }
            }

            if (!string.IsNullOrWhiteSpace(endTime))
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(endTime, out dt))
                {
                    where = where.AndAlso(m => m.FinishTime <= dt);
                }
            }
            Func<SimpleVoucher, int> order = m => m.ID;
            int rowCount = 0;
            var list = CVoucher.GetVoucherListByID(customFormID, limit, page, where, SimpleVoucher.Map_Manage, order, false, ref rowCount);
            var result = new
            {
                code = "0",
                msg = "",
                count = rowCount,
                data = list
            };
            return Json(result);
        }

        [MyActionFilter("888", "customFormID")]
        public IActionResult Show(int customFormID,int id)
        {
            string empID = base.EmpID;
            Voucher infoVoucher = CVoucher.GetVoucherByID(customFormID, id);
            if (infoVoucher == null)
            {
                return Redirect("/Member/Tips/Index?msg=该单据不存在");
            }

            EmployeeCustomForm infoEmployeeCustomForm = this.dbContextFactory.DbContext.EmployeeCustomForm.Where(m => m.EmpID == empID && m.CustomFormID == infoVoucher.CustomFormID && m.Status != -1 && m.TypeID == 1).FirstOrDefault();
            if (infoEmployeeCustomForm == null)
            {
                return Redirect("/Member/Tips/Index?msg=您没有当前单据的统计汇总权限");
            }

            CustomForm infoCustomForm = this.dbContextFactory.GetInfo<CustomForm>(infoVoucher.CustomFormID);

            if (infoCustomForm == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程不存在");
            }

            FormGroup infoFormGroup = this.dbContextFactory.DbContext.FormGroup.Where(m => m.ID == infoCustomForm.FormGroupID).FirstOrDefault();
            if (infoFormGroup == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程分组不存在");
            }
            ViewBag.FormGroup = infoFormGroup;

            CustomFormExtendInfo extendInfo = null;
            if (!string.IsNullOrWhiteSpace(infoCustomForm.ExtendField))
            {
                extendInfo = JsonHelper.DeserializeObj<CustomFormExtendInfo>(infoCustomForm.ExtendField);
            }

            if (extendInfo == null)
            {
                extendInfo = new CustomFormExtendInfo();
            }
            CVoucher objVoucher = new CVoucher();
            objVoucher.Map(infoVoucher, infoCustomForm,_cache);

            //ExtensionResultInfo infoExtensionResult = new ExtensionResultInfo();
            //if (!string.IsNullOrWhiteSpace(infoVoucher.Extension))
            //{
            //    infoExtensionResult = JsonHelper.DeserializeObj<ExtensionResultInfo>(infoVoucher.Extension);
            //}

            //if (infoExtensionResult == null) { infoExtensionResult = new ExtensionResultInfo(); }

            ViewBag.CustomForm = infoCustomForm;
            ViewBag.CustomFormExtendInfo = extendInfo;
            ViewBag.PageKey = "888"+ infoCustomForm.ID.ToString("D3");
            ViewBag.Type = "statistic";
            if (infoCustomForm.IsCustomView && !string.IsNullOrWhiteSpace(infoCustomForm.PrintTemplate))
            {
                string printTemplate = infoCustomForm.PrintTemplate;
                printTemplate = printTemplate.Replace("CIYUN_No_BarCode", $"<img id='barcode' style='width:180px;' /><script>JsBarcode('#barcode','{infoVoucher.No}');</script>");
                printTemplate = printTemplate.Replace("CIYUN_No_QRCode", "<div id='qrcode' style='width:80px;height:80px;margin:5px auto;overflow:hidden'></div><script type='text/javascript'>var qrcode = new QRCode(document.getElementById('qrcode'), { width: 80, height: 80 }); qrcode.makeCode('" + infoVoucher.No + "');</script>");
                printTemplate = printTemplate.Replace("CIYUN_SponsorName", infoVoucher.SponsorName);

                CacheHelper cacheHelper = new CacheHelper(_cache);
                List<Department> listDepartment = cacheHelper.GetDepartments();

                printTemplate = printTemplate.Replace("CIYUN_DepartmentName", CDepartment.GetFullDepartmentNameByID(infoVoucher.DepartmentID, listDepartment));


                Type t = infoVoucher.GetType();
                PropertyInfo[] PropertyList = t.GetProperties();

                foreach (PropertyInfo item in PropertyList)
                {
                    string name = item.Name;
                    object value = item.GetValue(infoVoucher, null);
                    if (value != null)
                    {
                        printTemplate = printTemplate.Replace("CIYUN_" + name, value.ToString());
                    }
                    else
                    {
                        printTemplate = printTemplate.Replace("CIYUN_" + name, "");
                    }
                }

                if (extendInfo != null && extendInfo.ListExtendField.Count > 0)
                {
                    foreach (var item in extendInfo.ListExtendField)
                    {
                        //item.Value = CommonHelper.GetDictionaryValueByKey(infoExtensionResult.DicExtend, item.Attribute);
                        printTemplate = printTemplate.Replace("CIYUN_" + item.Attribute, item.Value);
                    }
                }
                ViewBag.PrintTemplate = printTemplate;
                return View("Show2", infoVoucher);
            }
            else
            {
                return View("~/Areas/Member/Views/CustomForm/Show.cshtml", infoVoucher);
            }

        }

        [MyActionFilter("888", "customFormID")]
        public void InintExport(int customFormID)
        {
            CustomForm infoCustomForm = this.GetInfo<CustomForm>(customFormID);

            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem() { Text = "编号", Value = "Title" });
            list.Add(new SelectListItem() { Text = "单据号", Value = "No" });
            list.Add(new SelectListItem() { Text = "标题", Value = "Title" });
            list.Add(new SelectListItem() { Text = "发起时间", Value = "ApplicationDate" });
            list.Add(new SelectListItem() { Text = "完成时间", Value = "FinishTime" });
            list.Add(new SelectListItem() { Text = "发起人", Value = "SponsorName" });
            list.Add(new SelectListItem() { Text = "岗位ID", Value = "PositionID" });
            list.Add(new SelectListItem() { Text = "部门ID", Value = "DepartmentID" });
            list.Add(new SelectListItem() { Text = "发起时间", Value = "ApplicationDate" });
            CustomFormExtendInfo infoCustomFormExtend = null;
            if (!string.IsNullOrWhiteSpace(infoCustomForm.ExtendField))
            {
                infoCustomFormExtend = JsonHelper.DeserializeObj<CustomFormExtendInfo>(infoCustomForm.ExtendField);
            }
            if (infoCustomFormExtend.ListExtendField != null && infoCustomFormExtend.ListExtendField.Count > 0)
            {
                foreach (ExtendField itemExtendField in infoCustomFormExtend.ListExtendField)
                {
                    if (itemExtendField.Type == 2)
                    {
                        list.Add(new SelectListItem() { Text = itemExtendField.Name + "(Number)", Value = itemExtendField.Attribute });
                    }
                    else
                    {
                        list.Add(new SelectListItem() { Text = itemExtendField.Name + "(String)", Value = itemExtendField.Attribute });
                    }
                }
            }


            if (infoCustomFormExtend.TableFields != null && infoCustomFormExtend.TableFields.Count > 0)
            {
                foreach (ExtendField itemExtendField in infoCustomFormExtend.TableFields)
                {
                    if (itemExtendField.Name.CompareTo(itemExtendField.ParentName) != 0)
                    {
                        itemExtendField.Name = itemExtendField.ParentName + "->" + itemExtendField.Name;
                    }
                    if (itemExtendField.Type == 2)
                    {
                        list.Add(new SelectListItem() { Text = itemExtendField.Name + "(Number)", Value = itemExtendField.Attribute });
                    }
                    else if (itemExtendField.Type == 68 || itemExtendField.Type == 69 || itemExtendField.Type == 70)
                    {

                        list.Add(new SelectListItem() { Text = itemExtendField.Name + "(Decimal)", Value = itemExtendField.Attribute });
                    }
                    else
                    {
                        list.Add(new SelectListItem() { Text = itemExtendField.Name + "(String)", Value = itemExtendField.Attribute });
                    }
                }

                if (infoCustomFormExtend.TableFields.Select(m => m.Type == 69).Count() > 0)
                {
                    list.Add(new SelectListItem() { Text = "总计(Decimal)", Value = "70" });
                }
            }
            list.Add(new SelectListItem() { Text = "描述", Value = "Description" });
            ViewBag.AllAttribute = list;
        }

        [HttpGet]
        [MyActionFilter("888", "customFormID")]
        public IActionResult Export(int customFormID, string empName, string startTime, string endTime)
        {
            InintExport(customFormID);
            ViewBag.CustomFormID = customFormID;
            ViewBag.EmpName = empName;
            ViewBag.StartTime = startTime;
            ViewBag.EndTime = endTime;
            return View();
        }

        [HttpPost]
        [MyActionFilter("888", "customFormID")]
        public IActionResult Export(List<string> fields, int customFormID, string empName, string startTime, string endTime)
        {
            if (fields == null || fields.Count == 0)
            {
                ViewBag.Msg = "请选择的导出字段为空";
                InintExport(customFormID);
                ViewBag.CustomFormID = customFormID;
                ViewBag.EmpName = empName;
                ViewBag.StartTime = startTime;
                ViewBag.EndTime = endTime;
                return View();
            }
            CustomForm infoCustomForm = this.GetInfo<CustomForm>(customFormID);
            if (infoCustomForm == null)
            {
                return Redirect("/Member/Tips/Index?msg=您查看的单据类型不存在");                 
            }
            ViewBag.CustomForm = infoCustomForm;
            ViewBag.CustomFormID = customFormID;
            ViewBag.EmpName = empName;
            ViewBag.CustomFormID = customFormID;
            ViewBag.StartTime = startTime;
            ViewBag.EndTime = endTime;

            string title = infoCustomForm.Name + "汇总";

            string empID = Info.EmpID;

            EmployeeCustomForm infoEmployeeCustomForm = this.dbContextFactory.DbContext.EmployeeCustomForm.Where(m => m.EmpID == empID && m.CustomFormID == customFormID && m.Status != -1 && m.TypeID == 1).FirstOrDefault();
            if (infoEmployeeCustomForm == null)
            {
                return Redirect("/Member/Tips/Index?msg=您没有当前单据的统计汇总权限");
            }
            Expression<Func<Voucher, bool>> where = m => m.Status == 4;
            if (!string.IsNullOrWhiteSpace(empName))
            {
                where = where.AndAlso(m => m.SponsorName == empName);
                title += $"，【发起人{empName}】";
            }

            if (!string.IsNullOrWhiteSpace(startTime))
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(startTime, out dt))
                {
                    where = where.AndAlso(m => m.FinishTime >= dt);
                    title += $"，【开始时间-{dt.ToString2()}】";
                }
            }

            if (!string.IsNullOrWhiteSpace(endTime))
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(endTime, out dt))
                {
                    where = where.AndAlso(m => m.FinishTime <= dt);
                    title += $"，【结束时间-{dt.ToString2()}】";
                }
            }
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customFormID);
            var result = dal.GetDbContext().Set<Voucher>().Where(where).OrderByDescending(m => m.ID).ToList();
            var ms = ExcelHelper.ExportCustomForm(title, infoCustomForm, result, fields);
            //return new FileStreamResult(ms, "application/vnd.ms-excel");
            return File(ms, "application/vnd.ms-excel", title + ".xls");

        }


        [HttpPost]
        [MyActionFilter("888", "customFormID")]
        public IActionResult Remark(int customFormID,int id, string remark)
        {
            BaseResult baseResult = new BaseResult();
            Voucher infoVoucher = this.dbContextFactory.DbContext.Voucher.Where(m => m.ID == id).FirstOrDefault();
            if (infoVoucher == null)
            {
                baseResult.State = 400;
                baseResult.Msg = "没有找到该单据信息";
                return Json(baseResult);
            }
            else
            {
                Voucher updateVoucher = new Voucher();
                updateVoucher.Remark = remark;
                this.Update<Voucher>(infoVoucher, updateVoucher, new string[] { "Remark" });
                return Json(baseResult);
            }
        }
    }
}
